package hotel.meituan.oversea.biz.controller;

import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.MeituanConstants;
import hotel.base.oversea.constant.enums.MtGoodsEnums;
import hotel.base.oversea.constant.quartz.UrlSwitchsEnums;
import hotel.base.oversea.utils.*;
import hotel.meituan.oversea.biz.config.service.RedisService;
import hotel.meituan.oversea.biz.mapper.MtHotelDetailMapper;
import hotel.meituan.oversea.biz.mapper.MtHotelDetailOperLogMapper;
import hotel.meituan.oversea.biz.mapper.MtHotelRoomBedInfoMapper;
import hotel.meituan.oversea.biz.mapper.MtHotelRoomMapper;
import hotel.meituan.oversea.biz.service.MtHotelGoodsService;
import hotel.meituan.oversea.biz.service.MtHotelOrderDealService;
import hotel.meituan.oversea.biz.service.MtHotelRoomNameService;
import hotel.meituan.oversea.biz.service.MtHotelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 执行美团涉及定时器相关数据还原或恢复
 * @author qiuyy
 * @date 2020-05-15
 */
@Slf4j
@RestController
@RequestMapping("/meituanDealDataFromJob")
@Api(value = "MeituanDealDataFromJobController", tags = {"美团酒店订单接口"})
public class MeituanDealDataFromJobController {
    @Autowired
    private MtHotelDetailMapper mtHotelDetailMapper;

    @Autowired
    private MtHotelService mtHotelService;

    @Autowired
    private MtHotelRoomMapper mtHotelRoomMapper;

    @Autowired
    private MtHotelRoomBedInfoMapper mtHotelRoomBedInfoMapper;

    @Autowired
    private MtHotelDetailOperLogMapper mtHotelDetailOperLogMapper;

    @Autowired
    private MtHotelGoodsService mtHotelGoodsService;

    @Autowired
    private MtHotelOrderDealService mtHotelOrderDealService;

    @Autowired
    private MtHotelRoomNameService mtHotelRoomNameService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RestTemplate restTemplate;
    @PostMapping("/test1")
    @ApiOperation(value = "恢复定时器美团订单详情已查询标识idsMap",notes="必须经过auth授权")
    private Result<Object> test() {
        log.info("===" + redisService.queueSize("redis_change_goods_data_many_hotel"));

        //测试代码
        String swOrderId = "swOrderId";

        String mtHotelId = "mtHotelId";

        String goodsId = "goodsId";

        String checkinDate = "2021-04-30 00:00:00";

        String checkoutDate = "2021-04-30 00:00:00";

        Integer roomnum = 1;

        Integer swTotalPrice = 100;


        Integer thisChildCode = MtGoodsEnums.DelayStatus.contains("库存不足");
        if(ObjectUtils.isEmpty(thisChildCode)){
            thisChildCode = MtGoodsEnums.DelayStatus.CHECK_OTHER.code();
        }
        //超亏损，拆单不足2，保存延时订单日志
        mtHotelOrderDealService.saveDelayLog(swOrderId,
                MtGoodsEnums.DelayParentStatus.CHECK.getCode(),MtGoodsEnums.DelayParentStatus.CHECK.getMsg(),thisChildCode,MtGoodsEnums.DelayStatus.getMsg(thisChildCode)//[试单失败]code返回不成功
                ,mtHotelId,
                String.valueOf(goodsId),checkinDate,checkoutDate,roomnum,swTotalPrice,null);

        return new Result();
    }
    @PostMapping("/all")
    @ApiOperation(value = "恢复定时器美团订单详情已查询标识idsMap",notes="必须经过auth授权")
    private List<Integer> all() {
        String goods_query_job_up_hotel_data = (String)redisService.get("goods_query_job_up_hotel_data");
        if(null != goods_query_job_up_hotel_data){
            List<Integer> ids = GsonUtils.jsonToList(goods_query_job_up_hotel_data,Integer.class);
            log.info("缓存中存在list，goods_query_job_up_hotel_data");
            if(null != ids && ids.size()>0){
                for (Integer hotelId:ids){
                    redisService.lPush(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS_FOR_RLPRICE,hotelId);
                }
            }else{
                log.error("Part Time Query Check Price Job {} 节点时间主动查询上架酒店产品价格定时器,redis中无售卖房型的美团酒店id数据，该次定时器主动更新价格推送跳过","11");
            }
            log.info("REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS_FOR_RLPRICE:"+redisService.queueSize(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS_FOR_RLPRICE));
            return null;
        }

        String switchHost = CommonUrlConstants.SWITCHS_HOST;
        String getUpMtHotel = switchHost+ UrlSwitchsEnums.checkFindPriceStatus.GET_UP_MT_HOTEL.getValue();//查询所有
        log.info("Part Time Query Check Price Job {} 节点时间主动查询上架酒店产品价格定时器 进入方法 findAscUpMtHotelId","11");
        //发起请求
        Map params = new HashMap();
        params.put("timestamp","111");//每次定时器调用接口传唯一timestamp，为了方便查询线程日志
        Result response = RestTemplateUtils.post(getUpMtHotel, JSON.toJSONString(params),restTemplate);
        if(response.getCode()==CommonConstants.SUCCESS){
            List<Integer> ids = GsonUtils.jsonToList(response.getData().toString(),Integer.class);
            redisService.setUnit("goods_query_job_up_hotel_data",GsonUtils.GsonString(ids),32L,TimeUnit.MINUTES);

            if(null != ids && ids.size()>0){
                for (Integer hotelId:ids){
                    redisService.lPush(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS_FOR_RLPRICE,hotelId);
                }
            }else{
                log.error("Part Time Query Check Price Job {} 节点时间主动查询上架酒店产品价格定时器,redis中无售卖房型的美团酒店id数据，该次定时器主动更新价格推送跳过","dd");
            }

        }
        log.info("REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS_FOR_RLPRICE:"+redisService.queueSize(MeituanConstants.REIDS_POP_ALL_SALE_ROOM_ABOUT_MT_HOTEL_IDS_FOR_RLPRICE));
        return null;
    }

//    @PostMapping("/findAscUpMtHotelId")
//    @ApiOperation(value = "恢复定时器美团订单详情已查询标识idsMap",notes="必须经过auth授权")
//    private List<String> findAscUpMtHotelId() {
//        redisService.remove(CallbackmtfpConstants.REDIS_KEY_GOODS_QUERY_JOB_UP_HOTEL_DATA_ASC);
//        String goods_query_job_up_hotel_data = (String)redisService.get(CallbackmtfpConstants.REDIS_KEY_GOODS_QUERY_JOB_UP_HOTEL_DATA_ASC);
//        if(null != goods_query_job_up_hotel_data){
//            List<String> list = GsonUtils.jsonToList(goods_query_job_up_hotel_data,String.class);
//            log.info("缓存中存在list，goods_query_job_up_hotel_data");
//            return list;
//        }
//
//        String host = CommonUrlConstants.FP_HOST;
//        String getUpMtHotel = host+ UrlFpEnums.priceStatus.GET_DESC_MT_HOTEL.getValue();//获取所有酒店
//        //发起请求
//        Map map = new HashMap();
//        map.put("domestic",0);
//        Result response = RestTemplateUtils.get(getUpMtHotel,map,restTemplate);
//        if(response.getCode()== CommonConstants.SUCCESS){
//            List<String> list = (List<String>)response.getData();
//            redisService.setUnit(CallbackmtfpConstants.REDIS_KEY_GOODS_QUERY_JOB_UP_HOTEL_DATA_ASC, GsonUtils.GsonString(list),30L,TimeUnit.MINUTES);
//            return list;
//        }
//        return null;
//    }


    /**
     * 用途: 主动查询（美团接口不包含endDate 包含startDate）
     * @return
     */
    public Integer getDaysCommonBaseSet() {
        return 3;
        /*String days = (String)redisService.get(CallbackConstants.SWMT_PRICE_STATUS_DAYS);
        if(ObjectUtils.isEmpty(days)){
            Result result = RestTemplateUtils.get(CommonUrlConstants.ADMIN_HOST+"/sysCommonBase/value/"+CallbackConstants.SWMT_PRICE_STATUS_DAYS,null,restTemplate);
            if(result.getCode() == CommonConstants.SUCCESS && !ObjectUtils.isEmpty(result.getData())){
                days = (String)result.getData();
                redisService.set(CallbackConstants.SWMT_PRICE_STATUS_DAYS,days);
                return Integer.valueOf(days);
            }else{
                SendUtils.dingMsgNotLog("获取基础配置days异常请排查",DateUtil.getCurrTime()+" 当前设置默认值价格房态查询3天 result="+GsonUtils.GsonString(result), MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
                return 3;//有异常默认3天并推送钉钉
            }
        }else{
            return Integer.valueOf(days);
        }*/
    }
    @PostMapping("/test")
    @ApiOperation(value = "恢复定时器美团订单详情已查询标识idsMap",notes="必须经过auth授权")
    public Result<Object> test2(){

        Map<String,Object> map = new HashMap<>();
        map.put("cancelRuleList",new ArrayList<>());
        log.info("SwUpdateCancelTask 调用携程更新取消规则，请求参数："+ GsonUtils.GsonString(map));
        Result response = RestTemplateUtils.post(CommonUrlConstants.SWITCHS_HOST+"/switchCreateRoom/pushRoomCancelRule",GsonUtils.GsonString(map),restTemplate);


        /*String newDayNotTimeArray = (String)map.get("key");
        String hourStr = (String)map.get("key2");
        //00_01//  指定新的一天的某段时间不载入 该新的一天，，00_01 新的一天的00点到01点不载入新的一天 02点再开始载入新的一天    endtime是包含的关系包含01点所有时间
        if(null != newDayNotTimeArray ){
            //String hourStr = "23";DateUtil.formatDate(new Date(),"HH");
            if(newDayNotTimeArray.contains(hourStr)){
                Integer nowHour = Integer.valueOf(hourStr);
                LinkedHashMap<Integer, Integer> notSaleHourMap = new LinkedHashMap<>();
                for (int i = 0; i < newDayNotTimeArray.split(",").length; i++) {
                    String s = newDayNotTimeArray.split(",")[i];
                    if(i== 0){
                        notSaleHourMap.put(Integer.valueOf(s),-1);//开始时间
                    }else if(i== newDayNotTimeArray.split(",").length-1){
                        notSaleHourMap.put(Integer.valueOf(s),-2);//结束时间
                    }else{
                        notSaleHourMap.put(Integer.valueOf(s),0);
                    }
                }
                if(null != notSaleHourMap && notSaleHourMap.size()>0){
                    if(null  == redisService.get("sw_mt_query_not_add_new_check_close")){
                        log.info("notSaleHourMap={}",GsonUtils.GsonString(notSaleHourMap));
                        if(null != notSaleHourMap && notSaleHourMap.size()>0){
                            if(null != notSaleHourMap.get(nowHour)){

                            }
                        }
                    }
                }
            }
        }*/

     /*   String switchHost = CommonUrlConstants.SWITCHS_HOST;
        String getUpMtHotel = switchHost+ UrlSwitchsEnums.checkFindPriceStatus.GET_ASC_MT_HOTEL.getValue();//"genre":1  获取rp酒店列表   0 获取房态酒店列表
        //发起请求
        Map params = new HashMap();
        params.put("genre",0);
        Result response = RestTemplateUtils.post(getUpMtHotel,JSON.toJSONString(params),restTemplate);
        if(response.getCode()==CommonConstants.SUCCESS){
            List<Integer> list = GsonUtils.jsonToList(response.getData().toString(),Integer.class);
            log.info("===");
        }*/

        return new Result<>("returen1234");
    }

    ////////////////////
    @PostMapping("/setOpsForListPushKeyValue")
    @ApiOperation(value = "缓存list追加指定keyvalue",notes="必须经过auth授权")
    public Result<Object> setOpsForListPushKeyValue(@RequestBody Map map){
        String key = (String)map.get("key");
        String value = (String)map.get("value");
        if(null == value && null == key){
            return new Result<>("参数异常",-1);
        }
        redisService.lPush(key,value);//MeituanConstants.REDIS_NOTIFY_GOODS_CHANGE_MANY_HOTEL,JSON.toJSONString(thisGoodsDataList));
        log.info("缓存list追加指定keyvalue,"+DateUtil.getCurrTime()+" key="+key+" value="+value);
        return new Result<>("成功",0);
    }

    @PostMapping("/getRedisByKey")
    @ApiOperation(value = "获取redis",notes="必须经过auth授权")
    public Result<Object> getRedisByKey(@RequestBody Map map){
        String key = (String)map.get("key");
        if(null != key){
            return new Result<>( redisService.get(key));
        }
        return new Result<>("成功11",0);
    }
    @PostMapping("/pushListRedisByKey")
    @ApiOperation(value = "获取redis",notes="必须经过auth授权")
    public Result<Object> pushListRedisByKey(@RequestBody Map map){
        String key = (String)map.get("key");
        String value = (String)map.get("value");
        if(null != key && null != value){
            redisService.lPush(key, value);//MeituanConstants.REDIS_NOTIFY_GOODS_STATE_CHANGE_MANY_HOTEL
            return new Result<>(redisService.queueSize(key));
        }
        return new Result<>("成功",0);
    }

    @PostMapping("/setStringValueRedisByKey")
    @ApiOperation(value = "设置redis",notes="必须经过auth授权")
    public Result<Object> setStringValueRedisByKey(@RequestBody Map map){
        String key = (String)map.get("key");
        String value = (String)map.get("value");

        if(null != key){
            redisService.set(key,value);
        }
        return new Result<>("成功",0);
    }
    @PostMapping("/getQueueSizeByKey")
    @ApiOperation(value = "获取队列size",notes="必须经过auth授权")
    public Result<Object> getQueueSizeByKey(@RequestBody Map map){
        String key = (String)map.get("key");
        Long s = 0L;
        if(null != key){
            s = redisService.queueSize(key);
        }
        return new Result<>("size="+s,0);
    }

    @PostMapping("/hmGet")
    @ApiOperation(value = "",notes="必须经过auth授权")
    public Result<Object> hmGet(@RequestBody Map map){
        String key = (String)map.get("key");
        Object key2 = map.get("key2");
        Object hmValue=null;
        if(null != key){
            hmValue = redisService.hmGet(key,key2);
        }
        return new Result<>("size="+hmValue,0);
    }

    @PostMapping("/hmEntries")
    @ApiOperation(value = "",notes="必须经过auth授权")
    public Result<Object> hmEntries(@RequestBody Map map){
        String key = (String)map.get("key");
        Object hmValue=null;
        if(null != key){
            hmValue = redisService.hmEntries(key);
        }
        return new Result<>("size="+hmValue,0);
    }

    @PostMapping("/getSetSizeByKey")
    @ApiOperation(value = "获取队列size",notes="必须经过auth授权")
    public Result<Object> getSetSizeByKey(@RequestBody Map map){
        String key = (String)map.get("key");
        Long s = 0L;
        if(null != key){
            s = redisService.SetSize(key);
        }
        return new Result<>("size="+s,0);
    }

    @PostMapping("/getHashSizeByKey")
    @ApiOperation(value = "获取队列size",notes="必须经过auth授权")
    public Result<Object> getHashSizeByKey(@RequestBody Map map){
        String key = (String)map.get("key");
        Long s = 0L;
        if(null != key){
            s = redisService.HashSize(key);
        }
        return new Result<>("size="+s,0);
    }


    @PostMapping("/setValueRedisByKey")
    @ApiOperation(value = "设置redis",notes="必须经过auth授权")
    public Result<Object> setIntegerValueRedisByKey(@RequestBody Map map){
        String key = (String)map.get("key");
        Object value = map.get("value");

        if(null != key){
            redisService.set(key,value);
        }
        return new Result<>("成功",0);
    }

    @PostMapping("/deleteValueRedisByKey")
    @ApiOperation(value = "删除redis",notes="必须经过auth授权")
    public Result<Object> deleteValueRedisByKey(@RequestBody Map map){
        String key = (String)map.get("key");
        if(null != key){
            redisService.remove(key);
        }
        return new Result<>("成功",0);
    }


}
